package com.javaear.zblog4java.system.controller;

import com.javaear.zblog4java.system.entity.UploadModel;
import com.javaear.zblog4java.system.plugin.mybatisplus.GeneralMapper;
import com.javaear.zblog4java.system.service.impl.ManagerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

/**
 * @author aooer
 */
@Controller
@RequestMapping("system/management")
public class ManagerController {

    @Autowired
    private ManagerService managerService;

    @Autowired
    private GeneralMapper generalMapper;

    @RequestMapping("*-management")
    public void query() {
        managerService.queryAll();
    }

    @RequestMapping("*-add")
    public String add() {
        return managerService.add();
    }

    @RequestMapping("*-edit")
    public String edit() {
        return managerService.edit();
    }

    @RequestMapping("*-remove")
    public String remove() {
        return managerService.remove();
    }

    @RequestMapping("upload-add")
    public String upload(HttpServletRequest request) {
        MultipartFile uploadFile = ((DefaultMultipartHttpServletRequest) request).getFile("uploadFile");
        if (!uploadFile.isEmpty()) {
            try {
                File targetFile = new File(System.getProperty("user.dir") + "\\uploadfile", uploadFile.getOriginalFilename());
                if (!targetFile.exists())
                    targetFile.mkdirs();
                uploadFile.transferTo(targetFile);
                UploadModel uploadModel = new UploadModel();
                uploadModel.setSource(targetFile.getPath());
                uploadModel.setSize((int) (uploadFile.getSize() / 1024));
                uploadModel.setName(uploadFile.getName());
                uploadModel.setMimeType(uploadFile.getOriginalFilename().substring(uploadFile.getOriginalFilename().lastIndexOf(".") + 1));
                generalMapper.insertSelective(uploadModel);
                return "redirect:upload-management.html";
            } catch (IOException e) {
                System.out.println("上传异常");
            }
        }
        return "redirect:upload-management.html";
    }
}
